package cn.lblbc.lottery

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 * 如想详细了解本应用是如何创建出来的，可以访问如下链接：
 * https://mp.weixin.qq.com/s?__biz=Mzg4ODEwODI4Mg==&mid=2247487634&idx=1&sn=74fe01ca89c686032e614b9eec97639d&chksm=cf817507f8f6fc1155044fe573ae9ab0e4fdf8e30d03701942592d9865e88e53bca108d0cb1c#rd
 */
class MainActivity : AppCompatActivity() {
    private val interval = 100L
    private var isStarted = false
    private var handler = Handler(Looper.getMainLooper())
    private lateinit var tv1: TextView
    private lateinit var tv2: TextView
    private lateinit var tv3: TextView
    private lateinit var tv4: TextView
    private lateinit var tv5: TextView
    private lateinit var tv6: TextView
    private lateinit var tv7: TextView
    private lateinit var tv8: TextView
    private lateinit var tv9: TextView
    private var views: MutableList<TextView> = mutableListOf()

    private var focusIndex = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tv1 = findViewById(R.id.tv1)
        tv2 = findViewById(R.id.tv2)
        tv3 = findViewById(R.id.tv3)
        tv4 = findViewById(R.id.tv4)
        tv5 = findViewById(R.id.tv5)
        tv6 = findViewById(R.id.tv6)
        tv7 = findViewById(R.id.tv7)
        tv8 = findViewById(R.id.tv8)
        tv9 = findViewById(R.id.tv9)

        views.add(tv1)
        views.add(tv2)
        views.add(tv3)
        views.add(tv6)
        views.add(tv9)
        views.add(tv8)
        views.add(tv7)
        views.add(tv4)

        tv5.setOnClickListener {
            startOrPause()
        }
    }

    private fun startOrPause() {
        if (isStarted) {
            handler.removeCallbacksAndMessages(null)
            tv5.text = "抽奖"
            views.forEach { it.setBackgroundResource(R.drawable.shape_gray) }
        } else {
            handler.postDelayed({ startRoll() }, interval)
            tv5.text = "停"
        }
        isStarted = !isStarted
    }

    private fun startRoll() {
        views.forEach { it.setBackgroundResource(R.drawable.shape_gray) }
        views[focusIndex].setBackgroundResource(R.drawable.shape_highlight)

        focusIndex++
        if (focusIndex >= views.size) {
            focusIndex = 0
        }
        handler.postDelayed({ startRoll() }, interval)
    }
}